﻿using System;
using System.Collections.Generic;


using Microsoft.Xna.Framework;
using OakEngine.AI.Steering;

namespace OakEngine.AI.Dynamic_Steering_Behavior
{
    public class Oak_BlendedSteering : Oak_DynBehavior
    {
        public struct BehaviorandWeight
        {
            public Oak_DynBehavior _behavior;
            public float _fWeight;

            public BehaviorandWeight(Oak_DynBehavior behavior, float weight = 1.0f)
            {
                _behavior = behavior;
                _fWeight = weight;
            }
        }

        public List<BehaviorandWeight> m_Behaviors;
        private Steering.Oak_Steering output;
        public Oak_BlendedSteering()
        {
            m_Behaviors = new List<BehaviorandWeight>();
            output = new Oak_Steering();
        }


        public override void UpdateSteeringMovement(Steering.Oak_Steering steer)
        {
            steer.ZeroOut();
            output.ZeroOut();
            // Go through all the behaviors
            float totalWeight = 0;
            
            foreach (var b in m_Behaviors)
            {
                // Make sure the children agent is set
                b._behavior.BehaviorAgent = this.BehaviorAgent;
                output.ZeroOut();

                // get the behavior steering and add it to the accumulator
                b._behavior.UpdateSteeringMovement(output);
                steer.ForwardVector += output.ForwardVector*b._fWeight;
                steer.Rotation += output.Rotation*b._fWeight;

                totalWeight += b._fWeight;
            }

            // Devide the Accumulated output by the total weight
            if (totalWeight > 0.0f)
            {
                totalWeight = 1.0f/totalWeight;
                steer.ForwardVector *= totalWeight;
                steer.Rotation *= totalWeight;
            }
        }
    }
}
